#include <Arduino.h>

#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <Adafruit_GFX.h>
#include <Adafruit_I2CDevice.h>

// Wi-Fi 配置
const char* ssid     = "xiaomiwifi";      // 你的 Wi-Fi 网络名
const char* password = "xayn@1216@ynxa";  // 你的 Wi-Fi 密码

// put function declarations here:
void getWeatherInfoFromGD(String);

void setup() {
  Serial.begin(115200);
  Serial.print("hahahahaha");
  WiFi.begin(ssid, password);

  // 连接 Wi-Fi
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected to Wi-Fi!");
}

void loop() {
  Serial.print("hahahahaha");
  getWeatherInfoFromGD("141182");
  delay(1000 * 60 * 5);

}

// 汾阳 141182
// 宝鸡市渭滨区 610302
// 雁塔区 610113

// 根据城市排序获取天气信息
void getWeatherInfoFromGD(String cityCode) {
  HTTPClient httpClient;
  // 高德天气 API 配置
  const String apiKey = "2ef1fd746ce5aa55bf54ccba5f37a868";   // 高德 API Key
  // 构造请求 URL
  String url = "https://restapi.amap.com/v3/weather/weatherInfo?key=" + apiKey + "&city=" + cityCode + "&extensions=base&output=json";

  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("Requesting weather data...");
    httpClient.begin(url);

    int httpCode = httpClient.GET();
    if (httpCode > 0) {
      String payload = httpClient.getString();
      Serial.println("Response:");
      Serial.println(payload);

      // 解析 JSON 数据
      DynamicJsonDocument doc(1024);
      deserializeJson(doc, payload);

      const char* province = doc["lives"][0]["province"];
      const char* city = doc["lives"][0]["city"];
      const char* weather = doc["lives"][0]["weather"];
      const char* temperature = doc["lives"][0]["temperature"];
      const char* windDirection = doc["lives"][0]["winddirection"];
      const char* windPower = doc["lives"][0]["windpower"];
      const char* humidity = doc["lives"][0]["humidity"];
      const char* reportTime = doc["lives"][0]["reporttime"];

      // 输出天气信息
      Serial.println("省: " + String(province));
      Serial.println("市: " + String(city));
      Serial.println("天气: " + String(weather));
      Serial.println("室外温度: " + String(temperature) + " °C");
      Serial.println("风向: " + String(windDirection));
      Serial.println("风力: " + String(windPower));
      Serial.println("室外适度: " + String(humidity) + " %");
      Serial.println("发布时间: " + String(reportTime));
    } else {
      Serial.println("Error on HTTP request");
    }
    httpClient.end();
  } else {
    Serial.println("Wi-Fi not connected");
  }
}